/**
 * 获取对象
 */
const player = $("#player");
let canPlay = false;
let playing = false;
let looping = false;
let count = 0;
let _data = {};
let source = "";

/**
 * 初始化
 */
(function () {
    message();
    //设置播放器样式
    setPlayerStyle();
    setPlayerSrc();
    checkPlayerStatus();
    checkSrcStatus();
})();

/**
 * 获取src
 */
function setPlayerSrc() {
    $.ajax({
        url: mainUrl + "/api/getMp4Url",
        type: "post",
        data: {
            source: source
        },
        success: function (res) {
            _data = res;
            if (res.mp4Url === "") {
                setPlayerSrc();
            } else {
                $("#player").attr("src", res.mp4Url);
                if (canPlay) {
                    start();
                }
            }
        },
        error: function () {
            console.log("接口访问失败");
        }
    });
}

/**
 * 播放视频
 */
function start() {
    player[0].play();
    playing = true;
    count++;
}

/**
 * 暂停
 */
function pause() {
    player[0].pause();
    playing = false;
}

/**
 * 检测视频是否结束
 */
function checkPlayerStatus() {
    const c = setInterval(function () {
        const playerStatus = player[0].ended;
        //如果结束，自动切换下一个视频
        if (playerStatus) {
            setPlayerSrc();
            //清除循环，等待5秒，防止跳视频
            clearInterval(c);
            setTimeout(checkPlayerStatus, 5000);
        }
    }, 500);
}

/**
 * 检测播放地址是否有效
 */
function checkSrcStatus() {
    player[0].onerror = function () {
        setPlayerSrc();
    }
}

/**
 * 设置播放器样式
 */
function setPlayerStyle() {
    const wHeight = $(window).height();
    player.attr("height", wHeight - 6);
    player.removeAttr("width");
    //高度自适应
    $(window).resize(function () {
        setPlayerStyle();
    });
}

/**
 * 弹窗
 */
function message() {
    layui.layer.open({
        title: "",
        type: 2,
        offset: 'auto',
        content: "../frame/msg.html",
        area: ["450px", "200px"],
        end: function (index, layero) {
            canPlay = true;
            start();
            layer.close(index);
        }
    });
    //设置播放器音量
    player[0].volume = 0.5
    //绑定按键
    $(window).keypress(function (e) {
        console.log(e.keyCode);
        //空格
        if (e.keyCode === 32) {
            if (playing) {
                pause();
            } else {
                start();
            }
        }
        //回车
        if (e.keyCode === 13) {
            looping = !looping;
            player.attr("loop", looping);
        }
        //e
        if (e.keyCode === 101) {
            pause();
            setPlayerSrc();
        }
    });

}
